package kin.system.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;







import kin.bean.system.Form;
import kin.bean.system.M2O;
import kin.bean.system.MyEnumType;
import kin.manager.system.FormManager;
import kin.system.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;




/**
 * 将Ext中Store的data数据转化为Java中的List
 * 
 * @author JLee v .10
 * @since 2011-2-25
 * @function 主要是为了ext中可编辑的grid实现批量添加与修改 将注解的地方放开可以测试一下
 */

public class Json2List {
	/*Object result = method.invoke(bean, (Object[])null);
	2	this.map.put(key, result==null?"":wrap(result));*/
	// 将Store中的data(即：多个record)转化为多个bean
	public static Object JSON4Hibernate(Class clazz, String json)
			throws Exception {

		List list = new ArrayList();

		JSONArray ja = JSONArray.fromObject(json);

		for (int i = 0; i < ja.size(); i++) {

			Object bean = clazz.newInstance();
			Class c = bean.getClass();
			Field[] fs = c.getDeclaredFields();

			JSONObject jsonObject = (JSONObject) ja.get(i);
			for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
				String key = (String) iter.next();
				String value = jsonObject.getString(key);
				LinkedHashMap<String, Object> lhm = new LinkedHashMap<String, Object>();
				lhm.put("form_name", c.getSimpleName());
				// System.out.println("formname:"+c.getSimpleName());
				FormManager me = (FormManager) ApplicationContextHelper
						.getBean("formManagerIMP");
				Form form = me.find(lhm, null,null);
				Set<M2O> s = null;

				s = form.getM2os();

				Iterator ite = s.iterator();
				// 为了父类赋值 适应继承 过来的ID
				if (key.contains("_id")) {
					if ((StringUtil.fristLetterLowerCase(c.getSimpleName()) + "_id")
							.equals(key)) {
						modifyId(
								bean,
								StringUtil.fristLetterLowerCase(c.getSimpleName()) + "_id", value);
					} 
						
					else {
					
						String pp = key.substring(0, key.lastIndexOf("_"));
						System.out.println("pp:"+pp);
					    Field fie = c.getDeclaredField(pp);
					    if(fie.getType().isEnum()){
					    	System.out.println("value:"+value);
							String cc=MyEnumType.format(Integer.parseInt(value));
							 System.out.println("enumname:"+MyEnumType.valueOf(cc).getMyEnumType_name());
							fie.setAccessible(true);
							fie.set(bean,  MyEnumType.valueOf(cc));
					    }else{

						while (ite.hasNext()) {
							M2O m2o = (M2O) ite.next();

							if ((m2o.getTargetEntity()).equals(StringUtil
									.fristLetterUpperCase(pp))) {
								// Object p=
								// Class.forName(m2o.getFull_name()).newInstance();

								Object pom = ApplicationContextHelper
										.getBean(m2o.getName() + "ManagerIMP");
								Object hh = null;
								try {
									hh = pom.getClass()
											.getMethod(
													"get",
													new Class[] { Serializable.class })
											.invoke(pom,
													Integer.parseInt(value));
								} catch (IllegalArgumentException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								} catch (SecurityException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								} catch (IllegalAccessException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								} catch (InvocationTargetException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								} catch (NoSuchMethodException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}

								Field fi = c.getDeclaredField(m2o.getName());
								fi.setAccessible(true);
								fi.set(bean, hh);
							}
						}

					}
					}
				}

				
				for (Field f : fs) {
					if (f.getName().equals(key)) {

						Object vType = convertValueType(bean, f, value);
						mf1(bean, f.getName(), vType);
					}
				}
			}
			list.add(bean);
		}
		return list;
	}

	// 对bean的属性进行判断，然后将JSON中的值转化为对应的类型
	private static Object convertValueType(Object o, Field f, String value)
			throws Exception {
		Object ov = null;
		String fieldTypeName = f.getType().getName();
		if (fieldTypeName.equals("int")
				|| fieldTypeName.equals("java.lang.Integer")) {
			ov = value != null && value != "null" && !"".equals(value) ? Integer
					.parseInt(value) : 0;
		} else if (fieldTypeName.equals("long")
				|| fieldTypeName.equals("java.lang.Long")) {
			ov = value != null && value != "null" && !"".equals(value) ? Long
					.parseLong(value) : null;
		} else if (fieldTypeName.equals("float")
				|| fieldTypeName.equals("java.lang.Float")) {
			ov = value != null && value != "null" && !"".equals(value) ? Float
					.parseFloat(value) : null;
		} else if (fieldTypeName.equals("double")
				|| fieldTypeName.equals("java.lang.Double")) {
			ov = value != null && value != "null" && !"".equals(value) ? Double
					.parseDouble(value) : null;
		} else if (fieldTypeName.equals("boolean")
				|| fieldTypeName.equals("java.lang.Boolean")) {
			ov = value != null && value != "null" && !"".equals(value) ? Boolean
					.parseBoolean(value) : null;
		} else if (fieldTypeName.equals("java.util.Date")) {
			String s = null;
			System.out.println("value:"+value);
			if(value.contains("T")){
			s=value.split("T")[0];
			//s.replaceAll("-","/");
			}else{
				s=value;
			}
			System.out.println("date1:"+s);
			/*if (value.length() > 11) {
				
				ov = value != null && value != "null" && !"".equals(value) ? new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss").parse(value) : null;
			}*/ 
				ov = s != null && s != "null" && !"".equals(s) ? new SimpleDateFormat(
						"yyyy-MM-dd").parse(s) : null;
			
		} else if (fieldTypeName.equals("java.lang.String")) {
			f.setAccessible(true);
			 //Object fieldValue=f.get(o);
			
			if("".equals(value.trim())||null==value.trim()){
				ov=(String)f.get(o);
				System.err.println("zzzzzzzzzzzzzzzzzzzzzzz"+f.get(o));
			}else{
			ov = (String) value;
			}
		}  else if(fieldTypeName.equals("java.util.Set")){
			
			System.out.println("set:"+value);
			
			System.out.println("lengeth:"+value.length());
			Set set = new HashSet();
			Object pom = ApplicationContextHelper.getBean(f.getName().substring(0,f.getName().length()-1) + "ManagerIMP");
			Object hh = null;
			if(value.contains("[")&&value.contains("]")){
				String v=value.substring(1, value.length()-1);
				System.out.println("ids:"+v);
				String [] ids=v.split(",");
				for(String id:ids){
					hh = pom.getClass().getMethod("load",new Class[] { Serializable.class }).invoke(pom,Integer.parseInt(id));
					
						set.add(hh);
					
				}
			}else{
				hh = pom.getClass().getMethod("load",new Class[] { Serializable.class }).invoke(pom,Integer.parseInt(value));
				
					set.add(hh);
				
			}
		
			//f.getName();
			//System.out.println(types.toString());
			/*Set set = null;
			
				
				try {
					hh = pom.getClass().getMethod("load",new Class[] { Serializable.class }).invoke(pom,Integer.parseInt(value));
					if(hh!=null){
						set.add(hh);
					}
				} catch (IllegalArgumentException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (SecurityException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (InvocationTargetException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (NoSuchMethodException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}*/
			ov=set;
			
		}else if (fieldTypeName.equals("java.lang.Object")) {
			ov = (Object) value;
		} /*else {
			Field oField = o.getClass().getDeclaredField(f.getName());
			if (oField != null) {
				oField.setAccessible(true);
				Object entity = oField.get(o);
				if (entity == null) {
					entity = oField.getType().newInstance();
				}
				ov = json2Object(value, entity);
			}
		}*/
		return ov;
	}

	// 将{name:"jlee",sex:"male",age:18,job:"student"}json格式付给bean中对应的Object属性
	public static Object json2Object(String json, Object entity)
			throws Exception {
		Class c = entity.getClass();
		Field[] fs = c.getDeclaredFields();
		if ("[".equals(json.substring(0, 1))) {
			json = json.substring(1);
		}
		if ("]".equals(json.substring(json.length() - 1))) {
			json = json.substring(0, json.length() - 1);
		}
		JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(json);
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			String value = jsonObject.getString(key);
			// 为了父类赋值 适应继承 过来的ID
			if ((StringUtil.fristLetterLowerCase(c.getSimpleName()) + "_id")
					.equals(key)) {
				modifyId(entity,
						StringUtil.fristLetterLowerCase(c.getSimpleName())
								+ "_id", value);
			}
			for (Field f : fs) {
				if (f.getName().equals(key)) {
					Object vType = convertValueType(entity, f, value);
					mf1(entity, f.getName(), vType);
				}
			}
		}
		return entity;
	}

	// 修改bean的属性值
	private static void mf1(Object o, String fieldName, Object newValue)
			throws Exception {
		Class c = o.getClass();
		Field f = c.getDeclaredField(fieldName);
		f.setAccessible(true);
		f.set(o, newValue);
	}

	// 修改父类的 ID 值
	private static void modifyId(Object bean, String fieldName, String value)
			throws Exception {
		Class c = bean.getClass().getSuperclass();
		// System.out.println("class:"+c.getSimpleName());
		Field[] array = c.getDeclaredFields();
		for (Field _f : array) {

			if (_f.getName().equals(fieldName)) {
				Field f = c.getDeclaredField(fieldName);
				Object vType = convertValueType(bean, f, value);
				f.setAccessible(true);
				f.set(bean, vType);
			}
		}
	}

	

}
